<?php

namespace app\admin\service;

use app\model\AdminMenu;
use app\common\Tree;

class MenuService
{
    private $menuModel;

    public function __construct(AdminMenu $menuModel)
    {
        $this->menuModel = $menuModel;
    }

    // 添加/编辑菜单
    public function edit($params)
    {
        if (empty($params['id'])) {
            $params['created_at'] = time();
        } else {
            $params['updated_at'] = time();
        }

        $id = $this->menuModel->edit($params);
        return $id;
    }

    // 菜单列表
    public function getList()
    {
        $data = $this->menuModel->getAllData();

        $result = (new Tree)->toFormatTree($data, 'name');
        return $result;
    }

    // 菜单删除
    public function delete($id)
    {
        $childData = $this->menuModel->getInfoByPid($id);

        if ($childData) {
            return ['message' => Error::MENU_EXISTS_CHILDREN_DATA];
        }
        $data = $this->menuModel->destroy($id);

        if (!$data) {
            return ['message' => Error::DELETE_FAIL];
        }
        return [];
    }

    // 获取菜单详情
    public function getMenuDetail($id)
    {
        $data = $this->menuModel->getInfoById($id, 'id, name, path, icon, hide, sort, pid');
        return $data;
    }

    // 获取所有菜单数据
    public function getAllMenuData()
    {
        $data = $this->menuModel->getAllData('id, name');
        return $data;
    }
}